/*
 * @Author: lihaogn
 * @Date: 2021-08-07 19:53:05
 * @LastEditTime: 2022-01-23 20:07:46
 * @LastEditor: lihaogn
 * @Description: axios 封装
 * @FilePath: \lix-admin-vue2\src\utils\request.js
 */

import axios from 'axios'
import { Notification } from 'element-ui'
import store from '@/store'

// Vue.prototype.$http = axios

// 使用自定义配置新建一个 axios 实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么

    // 添加 token 信息
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }

    return config
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    if (response.data.success === false) {
      Notification.error({
        title: response.data.message.title || '错误',
        message: response.data.message.content || response.data.message
      })
    }
    return response
  },
  function(error) {
    // 对响应错误做点什么
    console.log('reponse error', error, 'message', error.message)
    handleResponseError(error)
    return { data: { success: false } }
  }
)

/**
 * @description: 处理 err 情况
 * @param {*} errResponse
 * @return {*}
 */
const handleResponseError = err => {
  let errResponse = err.response
  if (errResponse === undefined) {
    if (err.message.includes('timeout')) {
      Notification.error({
        title: '异常',
        message: '请求超时，请重试'
      })
    }
    return
  }
  if (errResponse.status == 500) {
    Notification.error({
      title: '错误',
      message: '500错误'
    })
  } else if (errResponse.status == 401) {
    Notification.error({
      title: '错误',
      message: '401错误-登录超时'
    })
    // 登出
    store.dispatch('user/logout')
  }
}

// get 请求
const getRequest = async (url, params) => {
  const res = await service.get(url, { params })
  return res.data
}

// post 请求
const postRequest = async (url, data) => {
  const res = await service.post(url, data)
  return res.data
}

// put 请求
const putRequest = async (url, data) => {
  const res = await service.put(url, data)
  return res.data
}

// delete 请求
const deleteRequest = async (url, params) => {
  const res = await service.delete(url, { params })
  return res.data
}

// 下载请求
const downloadRequest = async (url, params) => {
  const res = await service.get(url, { params, responseType: 'blob' })
  return res
}

export { getRequest, postRequest, putRequest, deleteRequest, downloadRequest }
